import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { BaseCrudService } from '../common/services/base-crud.service';
import { Agent } from './entities/agent.entity';
import { PaginationDto } from '../common/dto/base.dto';
import { ApiResponse, PaginationResult } from '../common/interfaces/base.interface';

@Injectable()
export class AgentsService extends BaseCrudService<Agent> {
  constructor(
    @InjectRepository(Agent)
    private agentRepository: Repository<Agent>,
  ) {
    super(agentRepository);
  }

  // 扩展：根据钱包地址查询
  async findByWallet(walletAddress: string): Promise<ApiResponse<Agent[]>> {
    try {
      const agents = await this.agentRepository.find({
        where: { walletAddress, isActive: true },
        relations: ['jobDistributions'],
      });

      return {
        success: true,
        data: agents,
        message: '查询成功'
      };
    } catch (error) {
      this.logger.error('Failed to find agents by wallet:', error);
      return {
        success: false,
        error: error.message || '查询失败'
      };
    }
  }

  // 扩展：搜索功能
  async search(params: {
    keyword?: string;
    tags?: string[];
    classification?: string;
    minReputation?: number;
    pagination: PaginationDto;
  }): Promise<ApiResponse<PaginationResult<Agent>>> {
    try {
      const { keyword, tags, classification, minReputation, pagination } = params;
      const { page, pageSize, sortBy, sortOrder } = pagination;
      const skip = (page - 1) * pageSize;

      const queryBuilder = this.agentRepository.createQueryBuilder('agent');

      // 基础过滤条件
      queryBuilder.where('agent.isActive = :isActive', { isActive: true });

      // 关键词搜索
      if (keyword) {
        queryBuilder.andWhere(
          '(agent.agentName ILIKE :keyword OR agent.description ILIKE :keyword)',
          { keyword: `%${keyword}%` }
        );
      }

      // 标签过滤
      if (tags && tags.length > 0) {
        queryBuilder.andWhere('agent.tags && :tags', { tags });
      }

      // 分类过滤
      if (classification) {
        queryBuilder.andWhere('agent.agentClassification = :classification', {
          classification,
        });
      }

      // 信誉过滤
      if (minReputation) {
        queryBuilder.andWhere('agent.reputation >= :minReputation', {
          minReputation,
        });
      }

      // 排序
      if (sortBy) {
        queryBuilder.orderBy(`agent.${sortBy}`, sortOrder);
      } else {
        queryBuilder.orderBy('agent.reputation', 'DESC');
      }

      // 分页
      queryBuilder.skip(skip).take(pageSize);

      const [data, total] = await queryBuilder.getManyAndCount();

      const result: PaginationResult<Agent> = {
        data,
        total,
        page,
        pageSize,
        totalPages: Math.ceil(total / pageSize),
      };

      return {
        success: true,
        data: result,
        message: '搜索成功'
      };
    } catch (error) {
      this.logger.error('Failed to search agents:', error);
      return {
        success: false,
        error: error.message || '搜索失败'
      };
    }
  }

  // 扩展：更新统计信息
  async updateStats(id: string, completed: boolean): Promise<ApiResponse<Agent>> {
    try {
      return await this.agentRepository.manager.transaction(async (manager) => {
        const agent = await manager.findOne(Agent, { where: { id } as any });
        
        if (!agent) {
          return {
            success: false,
            error: `ID为 ${id} 的Agent不存在`
          };
        }

        const totalJobs = agent.totalJobsCompleted + 1;
        const successfulJobs = completed
          ? agent.successRate * agent.totalJobsCompleted + 1
          : agent.successRate * agent.totalJobsCompleted;

        agent.totalJobsCompleted = totalJobs;
        agent.successRate = successfulJobs / totalJobs;
        agent.reputation = Math.min(10, agent.reputation + (completed ? 0.1 : -0.05));

        const updatedAgent = await manager.save(agent);

        return {
          success: true,
          data: updatedAgent,
          message: '统计信息更新成功'
        };
      });
    } catch (error) {
      this.logger.error('Failed to update agent stats:', error);
      return {
        success: false,
        error: error.message || '更新统计信息失败'
      };
    }
  }
}